﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows;

namespace DXApplicationTangche.Utils
{
    public class FileUtil
    {
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="picUrl">图片Http地址</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="timeOut">Request最大请求时间，如果为-1则无限制</param>
        /// <returns>是否下载成功</returns>
        public static bool DownloadPicture(string picUrl, string savePath, int timeOut)
        {
            bool value = false;
            WebResponse response = null;
            Stream stream = null;
            try
            {
                //输入图片url，初始化新的 WebRequest 实例request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
                if (timeOut != -1) request.Timeout = timeOut;
                //返回网络请求响应
                response = request.GetResponse();
                //从 Internet 资源返回数据流
                stream = response.GetResponseStream();
                //如果发送的请求数据内容类型非text开始，则保存二进制文件
                if (!response.ContentType.ToLower().StartsWith("text/"))
                    //保存二进制文件
                    value = SaveBinaryFile(response, savePath);
            }
            finally
            {
                //关闭流，释放资源
                if (stream != null) stream.Close();
                if (response != null) response.Close();
            }
            return value;
        }
        /// <summary>
        /// 保存二进制文件
        /// </summary>
        /// <param name="response"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        private static bool SaveBinaryFile(WebResponse response, string savePath)
        {
            bool value = false;
            byte[] buffer = new byte[1024];
            Stream outStream = null;
            Stream inStream = null;
            try
            {
                //保存路径如果存在该文件，删除
                if (File.Exists(savePath)) File.Delete(savePath);
                //输出流，指定文件路径
                outStream = System.IO.File.Create(savePath);
                //输入流，从 Internet 资源获取数据流
                inStream = response.GetResponseStream();              
                int l;
                do
                {
                    //读取字节流里的数据，位置下标从0开始，最多读取buffer.Length个字节的数据，将读取的数据存到buffer缓冲
                    //如果流已经读完，返回0
                    l = inStream.Read(buffer, 0, buffer.Length);
                    //将数据写入流，从下标0开始，每次取1个字节写入流
                    if (l > 0) outStream.Write(buffer, 0, l);
                } while (l > 0);
                //写入完毕，返回true
                value = true;
            }
            finally
            {
                //关闭字节流，释放资源
                if (outStream != null) outStream.Close();
                if (inStream != null) inStream.Close();
            }
            return value;
        }

        /// <summary>
        /// 获取文件MD5值
        /// </summary>
        /// <param name="fileName">文件绝对路径</param>
        /// <returns>MD5值</returns>
        public static string GetMD5HashFromFile(string fileName)
        {
            try
            {
                FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < retVal.Length; i++)
                {
                    sb.Append(retVal[i].ToString("x2"));
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
            }
        }
        /// <summary>
        /// 判断文件路径是否存在
        /// </summary>
        /// <param name="filePath">相对路径</param>
        /// <returns>文件是否存在</returns>
        public static bool FileExist(String filePath)
        {
            return System.IO.File.Exists(filePath);
        }

        /// <summary>
        /// 获取文件绝对路径
        /// </summary>
        /// <param name="filePath">相对路径</param>
        /// <returns>文件绝对路径</returns>
        public static String getAbsolutePath(String filePath)
        {
            //文件存在时有绝对路径
            if (System.IO.File.Exists(filePath))
            {
                return System.AppDomain.CurrentDomain.BaseDirectory + filePath;
            }
            //文件不存在
            else
            {
                return "文件不存在";
            }
        }

        /// <summary>
        /// 获取文件名，不带后缀
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String getFileName(String filePath)
        {
            return Path.GetFileNameWithoutExtension(filePath);
        }

        /// <summary>
        /// 获取文件后缀名
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String getExtensionName(String filePath)
        {
            return Path.GetExtension(filePath);
        }
        /// <summary>
        /// 获取文件根目录
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String GetPathRoot(String filePath)
        {
            return Path.GetPathRoot(filePath);
        }
        /// <summary>
        /// 获取文件所在目录
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String GetDirectoryName(String filePath)
        {
            return Path.GetDirectoryName(filePath);
        }
        /// <summary>
        /// 根据文件格式读取内容
        /// </summary>
        /// <param name="filePath">路径</param>
        /// <param name="fileType">格式</param>
        /// <returns></returns>
        public static string ReadFile(string filePath, string fileType)
        {
            try
            {
                string content = "文件格式不支持检索";
                filePath = HttpContext.Current.Server.MapPath(filePath);
                if (fileType == ".txt")
                {
                    StreamReader sr = new StreamReader(filePath);
                    content = sr.ReadToEnd().ToString();
                    sr.Close();
                }
                return content;
            }
            catch (Exception e)
            {
                return "对不起，本文没有发现！可能是从服务器上删除的。";
            }
        }
        /// <summary>
        /// 读取文本文档内容
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static String ReadTxtFile(string filePath)
        {
            return System.IO.File.ReadAllText(filePath);
        }
        
        /// <summary>
        /// 读csv转至List<String>
        /// </summary>
        /// <param name="strpath"></param>
        /// <returns></returns>
        public static List<String> readCsvTxtToList(string strpath)
        {
            List<String> csv解析 = new List<string>();
            string strline;
            StreamReader streamReader = new System.IO.StreamReader(strpath);
            while ((strline = streamReader.ReadLine()) != null)
            {
                csv解析.Add(strline);
            }
            return csv解析;
        }
    }
}
